package com.wt.springboot.demo.custom.components.requestmonitor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

/**
 * @author wangtao
 * @date 2023/3/11 21:58
 **/
public class TraceUtil {

    private static final Logger LOG = LoggerFactory.getLogger(TraceUtil.class);

    public static final String TRACE_ID_KEY = "trace-id";

    public static void setTraceId(String traceId) {
        try {
            // 设置traceId
            MDC.put(TRACE_ID_KEY, traceId);
        } catch (Exception e) {
            LOG.error("set traceId exception.msg={}.", e.getMessage(), e);
        }
    }

    public static String getTraceId() {
        try {
            // 获取traceId
            return MDC.get(TRACE_ID_KEY);
        } catch (Exception e) {
            LOG.error("get traceId exception.msg={}.", e.getMessage(), e);
        }
        return null;
    }

    public static void clear() {
        try {
            // 清除traceId
            MDC.clear();
        } catch (Exception e) {
            LOG.error("clear traceId exception.msg={}.", e.getMessage(), e);
        }
    }
}
